package noveiras;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import au.id.jericho.lib.html.Source;

public class TableTeste {

	private Shell sShell = null;  //  @jve:decl-index=0:visual-constraint="10,10"
	private StyledText styledText = null;
	private Table table = null;
	private SashForm sashForm = null;
	private Composite composite = null;
	private Composite composite1 = null;
	private TabFolder tabFolder = null;
	private HashMap<String, ArrayList> sourcesTabela = null;

	private void createSashForm() {
		sashForm = new SashForm(tabFolder, SWT.NONE);
		createComposite();
		createComposite1();
	}

	private void createComposite() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;
		composite = new Composite(sashForm, SWT.NONE);
		composite.setLayout(new GridLayout());
		composite.setLayoutData(gridData);
	}

	private void createComposite1() {
		composite1 = new Composite(sashForm, SWT.NONE);
		FillLayout fill = new FillLayout();
		fill.type = org.eclipse.swt.SWT.HORIZONTAL;
		composite1.setLayout(fill);
	}

	private void createTabFolder() {
		tabFolder = new TabFolder(sShell, SWT.NONE);
		createSashForm();
	}

	public static void main(String[] args) {
		Display display = Display.getDefault();
		TableTeste thisClass = new TableTeste();
		thisClass.createSShell();
		thisClass.sShell.open();


		while (!thisClass.sShell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

	private void createSShell() {
		FillLayout fillLayout = new FillLayout();
		fillLayout.spacing = 2;
		fillLayout.marginWidth = 2;
		fillLayout.type = org.eclipse.swt.SWT.HORIZONTAL;
		fillLayout.marginHeight = 2;
		sShell = new Shell(SWT.SHELL_TRIM);
		sShell.setText("Shell");
		sShell.setLayout(fillLayout);
		sShell.setSize(500, 500);
		sShell.setSize(new Point(181, 136));
		createTabFolder();

		if (sourcesTabela == null)
			sourcesTabela = new HashMap<String, ArrayList>();

		sShell.setSize(800,600);
		try {
			gerarTabela("epij","data/epij.txt.html");
			gerarTabela("rankpep","data/rankpep.html");
			gerarTabela("syfpeithi","data/syfpeithi.html");
			//gerarTabela("data/hlabind.html");
			consolidarGui();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void consolidarGui() {

		/*
		Iterator<String> iter = sourcesTabela.keySet().iterator();
		String hashKey = "";
		ArrayList<String> hashValue = null;
		while (iter.hasNext()) {

			hashKey = (String) iter.next();
			hashValue = sourcesTabela.get(hashKey); //tabela com todas as linhas
			String strTmp[] = null;
			for (int i=0;i<hashValue.size(); i++) {

				strTmp = hashValue.get(i).split("\t"); //111 \t JWHZMWOJ \t 20%
				System.out.println(strTmp.length);
				for (int j=0;j<strTmp.length;j++) {

					//System.out.println(j + " --> " +strTmp[j].length());

				}
			}
		}
		 */
	}

	private boolean tamanhosIguais(TableColumn col) {
		//col.
		return false;
	}

	public void consolidarGui(Table t) {

		System.out.println(t.getItems().length);
		TableItem tItem[] = t.getItems();

		System.out.println(t.getItem(0).getText());
		System.out.println(t.getItem(1).getText());
		System.out.println(t.getItem(2).getText());

	}

	ArrayList<Table> listaTabelas = new ArrayList<Table>();

	private void gerarTabela(String nome, String sourceUrlString) throws Exception {
		createSashForm();

		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.BEGINNING;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.verticalAlignment = GridData.BEGINNING;
		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.verticalAlignment = GridData.FILL;
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;

		Button button = new Button(composite, SWT.NONE);
		button.setLayoutData(gridData2);
		button.setText("Salvar todos os resultados");

		table = new Table(composite1, SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		styledText = new StyledText(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		styledText.setEditable(true);
		styledText.setLayoutData(gridData1);

		TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setControl(sashForm);

		ArrayList<String> l = new ArrayList<String>();
		ArrayList<String> linhasTabela = new ArrayList<String>();
		int maior = 0;
		String tmp = null;
		String[] stringTab = null;
		String tmpTab[] = null;

		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;
		Source source=new Source(new URL(sourceUrlString));
		String renderedText=source.getRenderer().toString();
		String[] linhas = renderedText.split("\n");

		//removendo linhas vazias
		for (int i=0; i< linhas.length; i++) {
			if (linhas[i].trim().length() > 0)
				l.add(linhas[i]);
		}

		//verificando qual a linha com maior numero de \t
		//para ser as linhas que vão para a Table
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");
				if (stringTab.length > maior)
					maior = stringTab.length;
			} 
		}


		//passando as informações nos seus devidos locais.
		for (int i=0; i< l.size(); i++) {
			tmp = l.get(i);
			if (tmp.contains("\t")) {
				stringTab = l.get(i).split("\t");

				if (stringTab.length == maior) {
					linhasTabela.add(tmp);
				} else {
					styledText.setText(styledText.getText()+tmp);
				}
			} else {
				styledText.setText(styledText.getText()+tmp);
			}
		}

		sourcesTabela.put(nome, linhasTabela);

		//adicionando as tabelas.
		for (int i=0;i<linhasTabela.size(); i++) {
			tmp = linhasTabela.get(i);
			tmpTab = tmp.split("\t");

			if (i==0) {
				for (int j=0; j<tmpTab.length; j++) {
					TableColumn column = new TableColumn (table, SWT.NONE);
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					column.setText(tmpTab[j]);
				}
			} else {
				final TableColumn [] columns = table.getColumns ();
				TableItem item = new TableItem (table, SWT.NONE);
				for (int j=0; j<columns.length; j++) {
					if (tmpTab[j].contains("\r")) {
						tmpTab[j] = tmpTab[j].replaceAll("\r", "");
					}
					item.setText (j, tmpTab[j]);
				}
			}
		}

		final TableColumn [] columns = table.getColumns();
		for (int i=0; i<columns.length; i++) 
			columns[i].pack();

		//consolidarGui(table);
		/*
		table.addListener (SWT.MouseDown, new Listener () {
			public void handleEvent (Event event) {
				Rectangle clientArea = table.getClientArea ();
				Point pt = new Point (event.x, event.y);
				int index = table.getTopIndex ();
				while (index < table.getItemCount ()) {
					boolean visible = false;
					TableItem item = table.getItem (index);
					for (int i=0; i < table.getColumnCount(); i++) {
						Rectangle rect = item.getBounds (i);
						if (rect.contains (pt)) {
							System.out.println ("Item " + index + "-" + i + " -- " + item.getText(i));
							table.setSelection(item);

						}
						if (!visible && rect.intersects (clientArea)) {
							visible = true;
						}
					}
					if (!visible) return;
					index++;
				}
			}
		});
		 */
		/*
		table.addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event event) {
				Point pt = new Point(event.x, event.y);
				TableItem item = table.getItem(pt);
				if (item == null)
					return;
				for (int i = 0; i < table.getColumnCount(); i++) {
					Rectangle rect = item.getBounds(i);
					if (rect.contains(pt)) {
						int index = table.indexOf(item);
						System.out.println("Item " + index + "-" + i + " --> " + item);
					}
				}
			}
		});
		 */
		listaTabelas.add(table);
		table.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				Table t = (Table)arg0.widget;
				String campo = "";
				boolean tudoCarac = true;
				int coluna=-1;
				int maiorTamanho = -1;
				for (int i=0; i<t.getColumnCount();i++) {
					tudoCarac = true;
					campo = t.getItem(t.getSelectionIndex()).getText(i);
					campo = campo.replaceAll("\t", "").replaceAll(" ", "").trim();
					for (int j=0;j<campo.length();j++)
						if (Character.isLetter(campo.charAt(j)) == false)
							tudoCarac = false;

					if (tudoCarac == true)
						if (campo.length() >= maiorTamanho) {
							maiorTamanho = campo.length();
							coluna = i;
						}

				}
				System.out.println("--> "+t.getItem(t.getSelectionIndex()).getText(coluna));
			}
		});
	}
}